package com.stupidzhe.ds.stack;

import java.util.Iterator;

/**
 * @Author: StupidZhe
 * @Date: Created in 2018/3/27
 * @Description:
 */
public class SimpleQueue implements Iterable<Integer> {

    // 容量
    private int capacity;

    private int currentCap;

    private int[] container;

    // 用于制作循环数组
    private int firstIndex;
    private int lastIndex;

    private int currentIndex;

    public SimpleQueue(int capacity) {
        this.capacity = capacity;
        container = new int[capacity];
        firstIndex = lastIndex = 0;
    }

    public Integer enqueue(int n) {
        currentCap++;
        if (currentCap > capacity) {
            return null;
        }
        container[firstIndex] = n;
        firstIndex = (firstIndex + 1) % capacity;
        return n;
    }

    public Integer dequeue() {
        currentCap--;
        if (currentCap < 0) {
            return null;
        }
        int n = container[lastIndex];
        lastIndex = (lastIndex + 1) % capacity;
        return n;
    }

    @Override
    public Iterator<Integer> iterator() {
        currentIndex = firstIndex;
        return new Iterator<Integer>() {
            @Override
            public boolean hasNext() {
                return currentIndex != lastIndex + capacity;
            }

            @Override
            public Integer next() {
                int res = container[currentIndex];
                currentIndex = currentIndex + 1;
                return res;
            }
        };
    }
}
